package com.hiultra.archive.device.door;

import com.gg.reader.api.dal.GClient;
import com.gg.reader.api.dal.HandlerGpiStart;
import com.gg.reader.api.dal.HandlerTagEpcLog;
import com.gg.reader.api.dal.HandlerTagEpcOver;
import com.gg.reader.api.protocol.gx.*;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ReadTagsGpiTrigger extends Thread {
    private int port = -1;
    private String ipPort;
    private GClient client;
    private static LogAppGpiStart firstLogAppGpiStart;
    // 是进还是出
    private static Boolean isIn = null;
    private static Boolean isReading = false;
    private static ExecutorService executorService = Executors.newSingleThreadExecutor();
    private static ExecutorService readService = Executors.newSingleThreadExecutor();


    public ReadTagsGpiTrigger(String ipPort) {
        this.ipPort = ipPort;
    }


    @Override
    public void run() {
        client = new GClient();
        if(client.openSerial485("COM29",3000)){
            //获取设备ip和端口号
            port = -1;
            subscribeHandler(client);
            System.out.println("启动成功！");
        } else {
            System.out.println("启动失败！");
        }
    }

    //订阅标签信息上报与gpi触发上报
    private synchronized void subscribeHandler(GClient client) {
        client.setSendHeartBeat(true);
        // 立式通道门
        // 配置需要先停止读卡
        MsgBaseStop baseStop = new MsgBaseStop();
        client.sendSynMsg(baseStop);

        // 经过开始读卡
        MsgAppSetGpiTrigger msgAppSetGpiTrigger1 = new MsgAppSetGpiTrigger();
        msgAppSetGpiTrigger1.setGpiPort(0);
        msgAppSetGpiTrigger1.setTriggerStart(2);
        msgAppSetGpiTrigger1.setTriggerOver(1);
//        msgAppSetGpiTrigger1.setOverDelayTime(300);
//        msgAppSetGpiTrigger1.setHexTriggerCommand("0001021000050000000101");
        client.sendSynMsg(msgAppSetGpiTrigger1);

        MsgAppSetGpiTrigger msgAppSetGpiTrigger2 = new MsgAppSetGpiTrigger();
        msgAppSetGpiTrigger2.setGpiPort(1);
        msgAppSetGpiTrigger2.setTriggerStart(2);
        msgAppSetGpiTrigger2.setTriggerOver(1);
        client.sendSynMsg(msgAppSetGpiTrigger2);

        client.onGpiStart = new HandlerGpiStart() {
            @Override
            public void log(String s, LogAppGpiStart logAppGpiStart) {
                System.out.println("GPI——Start:" + logAppGpiStart.getGpiPort());
                if (firstLogAppGpiStart != null && logAppGpiStart.getSystemTime().getTime() - firstLogAppGpiStart.getSystemTime().getTime() > 3000) {
                    firstLogAppGpiStart = null;
                    isIn = null;
                }
                if (firstLogAppGpiStart == null) {
                    firstLogAppGpiStart = logAppGpiStart;
                } else if (firstLogAppGpiStart.getGpiPort() != logAppGpiStart.getGpiPort()) {
                    if (isIn != null) {
                        return;
                    } else {
//                        tagSet.clear();
                    }
                    // false 主门在右侧 ，true 主门在左侧
                    boolean direction = true;
                    isIn = firstLogAppGpiStart.getGpiPort() == (direction ? 0 : 1);

                    System.out.println(isIn ? "进" : "出");
                } else {
                    firstLogAppGpiStart = logAppGpiStart;
                }
                startReadService();
            }
        };

        //
        System.out.println("数据接收成功！");
        client.onTagEpcLog = new HandlerTagEpcLog() {
            @Override
            public void log(String s, LogBaseEpcInfo logBaseEpcInfo) {
//                    System.out.println("epc:" + epcInfo.getEpc() + "   " + epcInfo.getAntId() + "  " + System.currentTimeMillis());
                tagLight(logBaseEpcInfo.getAntId());
                if (logBaseEpcInfo.getEpc() != null && !logBaseEpcInfo.getEpc().isEmpty()) {
//                    tagSet.add(new TagInfo(logBaseEpcInfo.getTid(), logBaseEpcInfo.getEpc(), System.currentTimeMillis()));
                }
            }
        };
        client.onTagEpcOver = new HandlerTagEpcOver() {
            @Override
            public void log(String s, LogBaseEpcOver logBaseEpcOver) {
                System.out.println("搜索标签结束");
            }
        };
        // 4个天线读卡, 读取EPC数据区以及TID数据区

//        MsgBaseInventoryEpc inventoryEpc = new MsgBaseInventoryEpc();
//        inventoryEpc.setAntennaEnable(EnumG.AntennaNo_1 | EnumG.AntennaNo_2 | EnumG.AntennaNo_3 | EnumG.AntennaNo_4);
//        // 0单次读取模式 1连续读取模式
//        inventoryEpc.setInventoryMode(1);
//        client.sendSynMsg(inventoryEpc);

    }

    private void startRead() {
        MsgBaseInventoryEpc inventoryEpc = new MsgBaseInventoryEpc();
        inventoryEpc.setAntennaEnable(EnumG.AntennaNo_1 | EnumG.AntennaNo_2 | EnumG.AntennaNo_3 | EnumG.AntennaNo_4);
        // 0单次读取模式 1连续读取模式
        inventoryEpc.setInventoryMode(1);
        client.sendSynMsg(inventoryEpc);
    }

    private void stopRead() {
        MsgBaseStop baseStop = new MsgBaseStop();
        client.sendSynMsg(baseStop);
    }

    private synchronized void startReadService() {
        if(!isReading) {
            readService.submit(new Runnable() {
                @Override
                public void run() {
                    isReading = true;
                    startRead();
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    stopRead();
                    isReading = false;
                }
            });
        }
    }

    private void tagLight(int ant) {

        executorService.submit(new Runnable() {
            @Override
            public void run() {
                if (client != null) {
                    MsgAppSetGpo msgAppSetGpo = new MsgAppSetGpo();
                    if (ant == 1 || ant == 2) {
                        msgAppSetGpo.setGpo2(1);
                    } else {
                        msgAppSetGpo.setGpo4(1);
                    }
                    client.sendSynMsg(msgAppSetGpo);
                    try {
                        Thread.sleep(1500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    if (ant == 1 || ant == 2) {
                        msgAppSetGpo.setGpo2(0);
                    } else {
                        msgAppSetGpo.setGpo4(0);
                    }

                    client.sendSynMsg(msgAppSetGpo);
                }
            }
        });
    }

    public static void main(String[] args) {

        GClient client = new GClient();
        if (client.openTcp("192.168.1.184:8160", 0)) {

            MsgAppSetGpo msgG = new MsgAppSetGpo();
            msgG.setGpo1(1);//gpo1 设置膏电平
            client.sendSynMsg(msgG);
            if (0x00 == msgG.getRtCode()) {
                System.out.println("Set success");
            } else {
                System.out.println(msgG.getRtMsg());
            }

            System.out.println("Press any key to continue setting the GPO");

            new Timer().schedule(new TimerTask() {
                @Override
                public void run() {
                    msgG.setGpo1(0);//gpo1 设置低电平
                    client.sendSynMsg(msgG);
                    if (0x00 == msgG.getRtCode()) {
                        System.out.println("Set success");
                    } else {
                        System.out.println(msgG.getRtMsg());
                    }
                }
            }, 5000);
        }
    }
}
